package br.com.goldentrade.util.table;

import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;

import javax.swing.DefaultCellEditor;
import javax.swing.InputMap;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

/**
 * 
 * @author rafael
 * 
 * Classe responsavel por realizar o controle do editor da tabela.
 * O editor default utilizado � o jTextField.
 * Realiza acoes default como selecionar o texto ao registrar focus na celula da tabela editaval.
 * Ao alterar o valor da celula realiza a acao TAB para alterar o celula de foco para a celula 
 * seguinte na tabela.
 *
 */
public class SimpleCellEditor extends DefaultCellEditor{

	boolean inFocus = false;
	TableBase table;
	public SimpleCellEditor(TableBase table, JTextField textField) {
		super(textField);
		this.table = table;
		setClickCountToStart(1);
		getTextField().addFocusListener(new FocusListener(){

			public void focusGained(FocusEvent e) {
				getTextField().select(0, getTextField().getText().length());
				inFocus=true;
			}

			public void focusLost(FocusEvent e) {}

		});

	}

	public JTextField getTextField(){
		return (JTextField)this.getComponent();
	}

	public boolean stopCellEditing() {
		boolean cellEditing = super.stopCellEditing();
		if(inFocus){
			InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
			if(im!=null){
				KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
				if(tab!=null){
					ActionEvent ae = new ActionEvent(table, 0, "");
					if(ae!=null){
						table.getActionMap().get(im.get(tab)).actionPerformed(ae);
						inFocus = false;
					}
				}
			}
		}
		return cellEditing;
	}
	
	/**
	 * Adiciona o SimpleCellEditor na tabela.
	 */
	public static void addSimpleCellEditor(TableBase table){
		table.setDefaultEditor(Object.class, new SimpleCellEditor(table, new JTextField()));
	}

	public boolean isInFocus() {
		return inFocus;
	}

	public void setInFocus(boolean inFocus) {
		this.inFocus = inFocus;
	}
}

